Page({
  data: {
    tabType: 0,
    tabs: [{
        key: 0,
        title: '行程安排',
        content: '行程安排',
      },
      {
        key: 1,
        title: '习惯打卡',
        content: '习惯打卡',
      },
      {
        key: 2,
        title: '目标',
        content: '目标',
      },
      {
        key: 3,
        title: '纪念日',
        content: '纪念日',
      },
    ],
    scheduleList: [],
    // 今日日程
    todaySchedule: [],
    // 未来日程
    clockList: [],
    // 今日打卡
    todayClock: [],
    targetList: [],
    // 正在进行的目标
    nowTarget: [],

    memorialdayList: [],

    // 是否展示添加控件的Flag
    showAddPanel: false,
    // 是否展示编辑控件的Flag
    showEditPanel: false,
    // 是否为编辑面板
    isEdit: false,
    // 传递给编辑面板的数据
    addPanelData: {},
    // 今天的日期字符串
    nowDateStr: ""
  },

  onload() {
    this.getUserProfile()
  },


  onShow() {
    // 初始化所有的记录
    this.initAllData()
    // 重置日期
  },

  changeTab(e) {
    // 获取事件参数
    const {
      index
    } = e.target.dataset

    //重新设置 tabType
    this.setData({
      tabType: index
    })
  },

  onTabsChange(e) {
    const {
      index
    } = e.detail
    const cindex = this.data.tabs.map((n) => n.key).indexOf(index)

    this.setData({
      tabType: index,
    })
  },

  onSwiperChange(e) {
    const {
      current: index,
      source
    } = e.detail
    // const { key } = this.data.tabs[index]

    if (!!source) {
      this.setData({
        // key,
        tabType: index,
      })
    }
  },

  // 待办事项的点击事件
  handelTapSchedule(e) {
    const {
      id
    } = e.target.dataset
    let scheduleList = this.data.scheduleList
    for (let i in scheduleList) {
      if (id == scheduleList[i].id) {
        // 找到被点击的item
        // 设置hidden相反
        scheduleList[i].hidden = !scheduleList[i].hidden
        // 更新data数据
        this.setData({
          scheduleList
        })
        return
      }
    }
  },

  // 拖动界面，将所有的 tool 隐藏
  handelTouchMove() {
    let scheduleList = this.data.scheduleList
    // 将所有的 hidden 设为 true
    for (let i in scheduleList) {
      scheduleList[i].hidden = true
    }
    // 更新 data
  },

  // 获取用户信息
  getUserProfile() {
    wx.getUserProfile({
      desc: '获取用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {}
    })
  },

  // 点击添加按钮事件-展示添加面板
  handleTapAdd(e) {
    // 展示模态框
    this.setData({
      showAddPanel: true,
    })
  },

  // 点击关闭或保存-添加面板
  handelTapAddExit(e) {
    const result = e.detail
    if (result == 'cancel') {
      // 关闭面板
      this.setData({
        showAddPanel: false
      })
      return
    } else if (result.flag == 'save') {
      delete result.flag
      // 调用云函数添加字段
      wx.showLoading({
        title: '请稍等',
        mask: true
      })
      wx.cloud.callFunction({
        name: 'addSchedule',
        data: {
          ...result
        },
        success: res => {
          wx.hideLoading({
            complete: (res) => {},
          })
          wx.showToast({
            title: '添加成功',
          })
          this.setData({
            showAddPanel: false
          })
          this.initAllData()

          // 重新获取当天数据
          this.refetchSchedule()
        }
      })
    }
  },


  // 点击添加事件中的日期按钮
  handelTapDate() {
    // 展示控件
    this.setData({
      showDatePanel: !this.data.showDatePanel
    })
  },

  // 点击添加事件中的时间按钮
  handelTapTime() {
    this.setData({
      showTimePanel: true
    })
  },

  // 子组件触发的exit
  handelTapDateExit(e) {
    const newDate = e.detail
    if (newDate == null) {
      this.setData({
        showDatePanel: false
      })
      return
    }
    // 设值
    this.setData({
      date: newDate,
      showDatePanel: false
    })
  },

  // 子组件触发TimeExit
  handelTapDateTimeExit(e) {
    const newTime = e.detail
    if (newTime == null) {
      this.setData({
        showTimePanel: false
      })
      return
    }
    // 设值
    this.setData({
      time: newTime,
      showTimePanel: false
    })
  },


  // scheduleList 子组件触发的handelEditSchedule
  handelEditSchedule(e) {
    let dataItem = e.detail
    let addPanelData = {
      ...dataItem
    }
    // 展示添加面板
    this.setData({
      showEditPanel: true,
      // 设置为编辑状态
      isEdit: true,
      addPanelData: addPanelData
    })
  },


  // 子组件触发关闭 editPanel
  handelTapEditExit(e) {
    const result = e.detail
    if (result == 'cancel') {
      // 关闭面板
      this.setData({
        showEditPanel: false
      })
      return
    } else if (result.flag == 'save') {
      delete result.flag
      wx.showLoading({
        title: '请稍等',
        mask: true
      })
      // 调用云函数进行修改
      wx.cloud.callFunction({
        name: 'updateSchedule',
        data: {
          ...result
        },
        success: res => {
          this.setData({
            showEditPanel: false,
          })
          this.initAllData()
          this.refetchSchedule()
          wx.hideLoading({
            complete: (res) => {},
          })
          // toast 提示
          wx.showToast({
            title: '修改成功',
            mask: true
          })
        },
        error: err => {
          wx.showToast({
            title: '错误',
            mask: true
          })
        }
      })
    }
  },

  // 点击打卡item 的事件
  handelTapClockItem(e) {
    let dataItem = e.target.dataset.item
    let addPanelData = {
      ...dataItem
    }
    // 展示添加面板
    this.setData({
      showEditPanel: true,
      // 设置为编辑状态
      isEdit: true,
      addPanelData: addPanelData
    })
  },

  // 点击目标item的事件
  handelTapTargetItem(e) {
    let dataItem = e.target.dataset.item
    let addPanelData = {
      ...dataItem
    }
    // 展示添加面板
    this.setData({
      showEditPanel: true,
      // 设置为编辑状态
      isEdit: true,
      addPanelData: addPanelData
    })
  },

  // 点击纪念日item的事件
  handelTapMamorialDayItem(e) {
    let dataItem = e.target.dataset.item
    let addPanelData = {
      ...dataItem
    }
    // 展示添加面板
    this.setData({
      showEditPanel: true,
      // 设置为编辑状态
      isEdit: true,
      addPanelData: addPanelData
    })
  },





  // 初始化所有数据
  initAllData() {
    this.refetchSchedule()
    this.initScheduleList()
    this.initClockList()
    this.initTargetList()
    this.initMemorialdayList()
    this.setData({
      showEditPanel: false,
      showAddPanel: false
    })
  },


  // 初始化scheduleList
  initScheduleList() {
    // 调用云函数进行查询
    wx.cloud.callFunction({
      name: 'queryAllSchedule',
      data: {
        type: 'schedule'
      },
      success: res => {
        // 循环找出当天的日程
        let scheduleList = res.result.data
        this.setData({
          scheduleList: scheduleList
        })

        // 保存在缓存中
        wx.setStorageSync('scheduleList', scheduleList)
        // let todaySchedule = scheduleList.filter(item => {
        //   let date = new Date(item.date)
        //   let today = new Date()
        //   if (item.circulation == 'daily') {
        //     return true
        //   } else if (item.circulation == 'weekly') {
        //     // 判断星期
        //     return today.getDay() == date.getDay()
        //   }
        //   // 判断是否是当天的日程
        //   else if (date.getFullYear() == today.getFullYear() &&
        //     date.getDate() == today.getDate() &&
        //     date.getMonth() == today.getMonth()) {
        //     return true
        //   }
        // })

        // // 时间排序
        // todaySchedule = todaySchedule.sort((a, b) => {
        //   let aHour = a.time.split(":")[0]
        //   let aMinute = a.time.split(":")[1]
        //   let bHour = b.time.split(":")[0]
        //   let bMinute = b.time.split(":")[1]
        //   if (aHour == bHour) {
        //     return aMinute - bMinute
        //   } else {
        //     return aHour - bHour
        //   }
        // })
      }
    })
  },

  // 初始化 clockList
  initClockList() {
    // 调用云函数进行查询
    wx.cloud.callFunction({
      name: 'queryAllClock',
      data: {
        type: 'clock'
      },
      success: res => {
        // 循环找出当天的日程
        let clockList = res.result.data
        let todayClock = clockList.filter(item => {
          let date = new Date(item.date)
          let today = new Date()
          if (item.circulation == 'daily') {
            return true
          } else if (item.circulation == 'weekly') {
            // 判断星期
            return today.getDay() == date.getDay()
          }
          // 判断是否是当天的日程
          if (date.getFullYear() == today.getFullYear() &&
            date.getDate() == today.getDate() &&
            date.getMonth() == today.getMonth()) {
            return true
          }
        })

        // 时间排序
        todayClock = todayClock.sort((a, b) => {
          let aHour = a.time.split(":")[0]
          let aMinute = a.time.split(":")[1]
          let bHour = b.time.split(":")[0]
          let bMinute = b.time.split(":")[1]
          if (aHour == bHour) {
            return aMinute - bMinute
          } else {
            return aHour - bHour
          }
        })


        this.setData({
          clockList: clockList,
          todayClock: todayClock
        })

        // 保存在缓存中
        wx.setStorageSync('clockList', clockList)
      }
    })
  },

  // 初始化target目标
  initTargetList() {
    // 调用云函数进行查询
    wx.cloud.callFunction({
      name: 'queryAllSchedule',
      data: {
        type: 'target'
      },
      success: res => {
        // 循环找出当天的日程
        let targetList = res.result.data
        let nowTarget = targetList.filter(item => {
          // 判断是否过期
          let today = new Date()
          let date = new Date(item.date)
          if (((today.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)) <= item.duringTime) {
            return true
          }
        })
        nowTarget = nowTarget.map(item => {
          // 判断是否当天已完成
          if (new Date(item.lastDate).toDateString() == new Date().toDateString()) {
            item.todayDone = true
          }
          return item
        })

        this.setData({
          targetList: targetList,
          nowTarget: nowTarget
        })

        // 保存在缓存中
        wx.setStorageSync('nowTarget', nowTarget)
      }
    })
  },


  // 初始化纪念日
  initMemorialdayList() {
    // 调用云函数进行查询
    wx.cloud.callFunction({
      name: 'queryAllSchedule',
      data: {
        type: 'memorialday'
      },
      success: res => {
        // 循环找出当天的日程
        let memorialdayList = res.result.data
        this.setData({
          memorialdayList: memorialdayList,
        })
      }
    })
  },

  // 日历选择日期事件
  selectDate(e) {
    let {
      year,
      month,
      day
    } = e.detail
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }
    let dateStr = year + '-' + month + '-' + day
    this.setData({
      nowDateStr: dateStr
    })
    wx.cloud.callFunction({
      name: 'queryScheduleByDate',
      data: {
        date: dateStr
      },
      success: res => {
        // 循环找出当天的日程
        let list = res.result.data
        let dayScheduleList = list.filter(todo => {
          // 日循环
          if (todo.circulation == 'daily') return true;
          // 周循环
          if (todo.circulation == 'weekly') {
            return new Date(todo.date).getDay() == new Date(dateStr).getDay()
          } else {
            return new Date(todo.date).toDateString() == new Date(dateStr).toDateString()
          }
        })
        this.setData({
          todaySchedule: dayScheduleList
        })
      }
    })
  },

  // 更新行程save
  refetchSchedule() {
    console.log(this.data.nowDateStr)
    let targetDate = new Date(this.data.nowDateStr)
    console.log(targetDate)
    let year = targetDate.getFullYear()
    let month = targetDate.getMonth() + 1
    let day = targetDate.getDate()
    let dateStr = year + '-' + month + '-' + day
    console.log(dateStr)
    wx.cloud.callFunction({
      name: 'queryScheduleByDate',
      data: {
        date: dateStr
      },
      success: res => {
        // 循环找出当天的日程
        let list = res.result.data
        let dayScheduleList = list.filter(todo => {
          // 日循环
          if (todo.circulation == 'daily') return true;
          // 周循环
          if (todo.circulation == 'weekly') {
            return new Date(todo.date).getDay() == new Date(dateStr).getDay()
          } else {
            return new Date(todo.date).toDateString() == new Date(dateStr).toDateString()
          }
        })
        this.setData({
          todaySchedule: dayScheduleList
        })
      }
    })
  }




  // // 测试清除打卡
  // testClearClock(){
  //   wx.cloud.callFunction({
  //     name:'clearClockDone',
  //     success:res=>{
  //     }
  //   })
  // }
})